﻿Imports System.Threading

Friend Class ReaderWriterSlimLock
  Implements ISharedCollectionLock
  Private _lock As ReaderWriterLockSlim
  Private _disposed As Boolean

  Public Sub New(ByVal lock As ReaderWriterLockSlim)
    _lock = lock
  End Sub

  Private Sub EnsureNotDisposed()
    If _disposed Then
      Throw New ObjectDisposedException("ReaderWriterSlimLock")
    End If
  End Sub

  Public Sub Dispose() Implements IDisposable.Dispose
    Dispose(True)

    GC.SuppressFinalize(Me)
  End Sub

  Protected Overridable Sub Dispose(ByVal disposing As Boolean)
    If Not _disposed Then
      If disposing Then
        'free managed resources here
      End If

      'free unmanaged resrources here
      If _lock.IsReadLockHeld Then
        _lock.ExitReadLock()
      ElseIf _lock.IsWriteLockHeld Then
        _lock.ExitWriteLock()
      ElseIf _lock.IsUpgradeableReadLockHeld Then
        _lock.ExitUpgradeableReadLock()
      End If

      _lock = Nothing
      _disposed = True
    End If
  End Sub

  Protected Overrides Sub Finalize()
    Dispose(False)
  End Sub
End Class
